import {
  defineComponent,
  ExtractPropTypes,
  onMounted,
  PropType,
  Ref,
  ref
} from 'vue'
import { FormEvents, WidgetOptions } from './types'
import { cloneDeep } from 'lodash-es'
import useToolButton from './hooks/useToolButton'
import useWidgetRender from './hooks/useWidgetRender'

const SpsFormPropsDefine = {
  options: {
    type: Array as PropType<WidgetOptions[]>,
    required: true
  },
  model: {
    type: Object,
    default: () => ({})
  },
  actions: {
    type: String,
    default: 'reset,submit'
  },
  formEvents: {
    type: Object as PropType<FormEvents>,
    default: () => ({})
  }
} as const

export type SpsFormProps = Partial<ExtractPropTypes<typeof SpsFormPropsDefine>>

export default defineComponent({
  name: 'SpsForm',
  props: SpsFormPropsDefine,
  emits: ['reset', 'submit'],
  setup(props, { attrs, emit }) {
    const model: Ref<any> = ref({})
    const { formRef, renderToolButton } = useToolButton(model, emit)
    const { renderWidget } = useWidgetRender()
    onMounted(() => {
      model.value = cloneDeep(props.model)
    })
    /* render 函数 */
    return () => {
      // 表单项
      const items = props.options.map((option) => {
        return (
          <a-form-item
            label={option.label}
            name={option.prop}
            rules={option.rules}>
            {renderWidget(model, option)}
          </a-form-item>
        )
      })
      return (
        <>
          <a-form class="sps-form" ref={formRef} model={model.value} {...attrs}>
            {items}
            <a-form-item class="sps-form-actions">
              {renderToolButton(props)}
            </a-form-item>
          </a-form>
        </>
      )
    }
  }
})
